package net.game.server.io;

import net.game.server.game.Position;
import net.game.server.game.player.Player;
import net.game.server.util.crypto.BASE64;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class PlayerWorker {
    
    public static void save(Player player) {
        try {
            RandomAccessFile file = new RandomAccessFile("player/" + BASE64.encode(player.getUsername()) + ".dat", "w");
            file.writeUTF(BASE64.encode(player.getPassword()));
            file.writeByte(player.getRights());
            file.writeInt(player.position().getX());
            file.writeInt(player.position().getY());
            file.writeByte(player.position().getZ());
            file.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Player load(String username, String pass, Channel channel) {
        ChannelBuffer buffer = ChannelBuffers.buffer(2);
        try {
            RandomAccessFile player = new RandomAccessFile("players/" + BASE64.encode(username) + ".dat", "r");
            String password = BASE64.decode(player.readUTF());
            if (password.equals(pass)) {
                byte rights = player.readByte();
                Position position = new Position(player.readInt(), player.readInt(), player.readByte());
                buffer.writeByte((byte) 0); 
                buffer.writeByte(rights);
                channel.write(buffer);
                return new Player(username, password, rights, position, channel);
            } else {
                buffer.writeByte((byte) 1);
                buffer.writeByte((byte) 0);
                channel.write(buffer);
            }
            player.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Player p = new Player(username, pass, (byte) 0, new Position(0,0,0), channel);
        save(p);
        return p;
    }
}
